package jsu.ljy.lostandfind.controller;

import jsu.ljy.lostandfind.common.Result;
import jsu.ljy.lostandfind.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 * 
 * <p>处理文件上传请求，支持图片文件的上传。</p>
 * 
 * @author 罗嘉毅
 * @version 1.0
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 处理文件上传请求
     * 
     * @param file 上传的文件
     * @return 包含文件URL的响应
     */
    @PostMapping
    public Result<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error(400, "未找到上传的文件");
            }

            String fileUrl = fileUploadUtil.handleFileUpload(file);
            Map<String, String> data = new HashMap<>();
            data.put("url", fileUrl);
            return Result.success(data);
        } catch (IllegalArgumentException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "文件上传失败：" + e.getMessage());
        }
    }
} 